package io.zhengsh.juc._3queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueTest {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<DelayObject> blockingQueue = new DelayQueue<DelayObject>();
        blockingQueue.put(new DelayObject("T1", 1000 * 1));
        blockingQueue.put(new DelayObject("T2", 1000 * 2));
        blockingQueue.put(new DelayObject("T3", 1000 * 3));
        blockingQueue.put(new DelayObject("T4", 1000 * 4));
        blockingQueue.put(new DelayObject("T5", 1000 * 5));


        DelayObject take1 = blockingQueue.take();
        System.out.println(take1.name);
        DelayObject take2 = blockingQueue.take();
        System.out.println(take2.name);
        DelayObject take3 = blockingQueue.take();
        System.out.println(take3.name);
        DelayObject take4 = blockingQueue.take();
        System.out.println(take4.name);
        DelayObject take5 = blockingQueue.take();
        System.out.println(take5.name);
    }

    public static class DelayObject implements Delayed {

        public String name;
        public Integer delayTime;

        public DelayObject(String name, Integer delayTime) {
            this.name = name;
            this.delayTime = delayTime;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(delayTime, TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            Integer delayTime = ((DelayObject) o).delayTime;
            return this.delayTime.compareTo(delayTime);
        }
    }
}
